package com.zmkj.cn.comm.util;

import com.zmkj.cn.comm.exception.BaseException;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


@Slf4j
public class ZipUtils {


    public static void createzip(List<File> fileList, String zipPath) throws BaseException {
        FileInputStream nFileInputStream = null;
        ZipOutputStream nZipOutputStream = null;
        try {
            if (zipPath != null && new File(zipPath).exists()) {
                FileOutputStream fileOutputStream = new FileOutputStream(zipPath);
                nZipOutputStream = new ZipOutputStream(fileOutputStream);
                for (File file : fileList) {
                    nFileInputStream = new FileInputStream(file);
                    nZipOutputStream.putNextEntry(new ZipEntry(file.getName()));
                    int len;
                    while ((len = nFileInputStream.read()) != -1) {
                        nZipOutputStream.write(len);
                        nZipOutputStream.flush();
                    }
                }
                nZipOutputStream.close();
                if (nFileInputStream != null) {
                    nFileInputStream.close();
                }
            }
            log.info("生成zip成功");
        } catch (Exception e1) {
            e1.printStackTrace();
            throw new BaseException("生成zip失败", "生成zip失败", -1);
        } finally {
            try {
                if (nFileInputStream != null) {
                    nFileInputStream.close();
                }
                if (nFileInputStream != null) {
                    nZipOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new BaseException("生成zip失败", "生成zip失败", -1);
            }
        }
    }
}
